<template>
  <div class="china-map-container">
    <!-- 科技风背景 -->
    <div class="tech-background">
      <div class="grid-lines"></div>
      <div class="floating-particles"></div>
    </div>
    
    <!-- 返回按钮 -->
    <button class="back-button" @click="goBack">
      <span class="back-icon">←</span>
      <span class="back-text">返回</span>
    </button>
    
    <div class="background-layers">
      <img 
        class="map-layer map-base" 
        :src="mapImage" 
        alt="中国地图背景"
      />
      <img 
        class="map-layer map-overlay rotating" 
        :src="lbxImage" 
        alt="地图装饰层"
      />
    </div>
    <div ref="chartRef" class="echarts-layer"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import mapImage from '../../assets/map.png'
import lbxImage from '../../assets/lbx.png'

const router = useRouter()

// 返回功能
const goBack = () => {
  router.push('/')
}

// 定义 props
interface Props {
  title?: string
  data?: Array<{ name: string; value: number }>
}

const props = withDefaults(defineProps<Props>(), {
  title: '中国数据分布图',
  data: () => [
    { name: '北京市', value: 21542 },
    { name: '天津市', value: 15618 },
    { name: '河北省', value: 74610 },
    { name: '山西省', value: 34835 },
    { name: '内蒙古自治区', value: 24049 },
    { name: '辽宁省', value: 42591 },
    { name: '吉林省', value: 26733 },
    { name: '黑龙江省', value: 37473 },
    { name: '上海市', value: 24281 },
    { name: '江苏省', value: 84748 },
    { name: '浙江省', value: 64567 },
    { name: '安徽省', value: 61027 },
    { name: '福建省', value: 41540 },
    { name: '江西省', value: 45188 },
    { name: '山东省', value: 101527 },
    { name: '河南省', value: 99365 },
    { name: '湖北省', value: 57752 },
    { name: '湖南省', value: 66444 },
    { name: '广东省', value: 126012 },
    { name: '广西壮族自治区', value: 50126 },
    { name: '海南省', value: 10081 },
    { name: '重庆市', value: 32054 },
    { name: '四川省', value: 83674 },
    { name: '贵州省', value: 38562 },
    { name: '云南省', value: 47209 },
    { name: '西藏自治区', value: 3648 },
    { name: '陕西省', value: 39528 },
    { name: '甘肃省', value: 25019 },
    { name: '青海省', value: 5923 },
    { name: '宁夏回族自治区', value: 7202 },
    { name: '新疆维吾尔自治区', value: 25852 },
    { name: '台湾省', value: 23561 },
    { name: '香港特别行政区', value: 7482 },
    { name: '澳门特别行政区', value: 6}
  ]
})

const chartRef = ref<HTMLDivElement>()
let myChart: echarts.ECharts | null = null
let colorAnimationTimer: number | null = null
let currentColorIndex = 0

// 流动颜色配置
const flowingColors = [
  // 蓝色系流动
  ['#1e3a8a', '#3b82f6', '#60a5fa', '#93c5fd', '#fbbf24', '#f59e0b', '#ea580c', '#dc2626', '#b91c1c'],
  // 青色系流动  
  ['#0891b2', '#06b6d4', '#67e8f9', '#a5f3fc', '#fbbf24', '#f59e0b', '#ea580c', '#dc2626', '#b91c1c'],
  // 紫色系流动
  ['#7c3aed', '#8b5cf6', '#a78bfa', '#c4b5fd', '#fbbf24', '#f59e0b', '#ea580c', '#dc2626', '#b91c1c'],
  // 绿色系流动
  ['#059669', '#10b981', '#34d399', '#6ee7b7', '#fbbf24', '#f59e0b', '#ea580c', '#dc2626', '#b91c1c'],
  // 橙色系流动
  ['#ea580c', '#f59e0b', '#fbbf24', '#fcd34d', '#60a5fa', '#3b82f6', '#1e3a8a', '#dc2626', '#b91c1c']
]

// 标准省份名称映射表
const provinceNameMap: Record<string, string[]> = {
  '北京': ['北京', '北京市'],
  '天津': ['天津', '天津市'],
  '河北': ['河北', '河北省'],
  '山西': ['山西', '山西省'],
  '内蒙古': ['内蒙古', '内蒙古自治区'],
  '辽宁': ['辽宁', '辽宁省'],
  '吉林': ['吉林', '吉林省'],
  '黑龙江': ['黑龙江', '黑龙江省'],
  '上海': ['上海', '上海市'],
  '江苏': ['江苏', '江苏省'],
  '浙江': ['浙江', '浙江省'],
  '安徽': ['安徽', '安徽省'],
  '福建': ['福建', '福建省'],
  '江西': ['江西', '江西省'],
  '山东': ['山东', '山东省'],
  '河南': ['河南', '河南省'],
  '湖北': ['湖北', '湖北省'],
  '湖南': ['湖南', '湖南省'],
  '广东': ['广东', '广东省'],
  '广西': ['广西', '广西壮族自治区'],
  '海南': ['海南', '海南省'],
  '重庆': ['重庆', '重庆市'],
  '四川': ['四川', '四川省'],
  '贵州': ['贵州', '贵州省'],
  '云南': ['云南', '云南省'],
  '西藏': ['西藏', '西藏自治区'],
  '陕西': ['陕西', '陕西省'],
  '甘肃': ['甘肃', '甘肃省'],
  '青海': ['青海', '青海省'],
  '宁夏': ['宁夏', '宁夏回族自治区'],
  '新疆': ['新疆', '新疆维吾尔自治区'],
  '台湾': ['台湾', '台湾省'],
  '香港': ['香港', '香港特别行政区'],
  '澳门': ['澳门', '澳门特别行政区']
}

// 使用传入的数据或默认数据
const chinaData = computed(() => {
  const mappedData: Array<{ name: string; value: number }> = []
  const addedNames = new Set<string>()
  
  props.data.forEach(item => {
    // 为每个数据项创建多个名称变体
    Object.entries(provinceNameMap).forEach(([standardName, variants]) => {
      if (variants.some(variant => variant === item.name)) {
        // 添加标准名称
        if (!addedNames.has(standardName)) {
          mappedData.push({ name: standardName, value: item.value })
          addedNames.add(standardName)
        }
        // 添加所有变体名称
        variants.forEach(variant => {
          if (!addedNames.has(variant)) {
            mappedData.push({ name: variant, value: item.value })
            addedNames.add(variant)
          }
        })
      }
    })
  })
  
  // 如果映射失败，使用原始数据
  if (mappedData.length === 0) {
    return props.data
  }
  
  return mappedData
})

const initChart = async () => {
  if (!chartRef.value) return
  
  myChart = echarts.init(chartRef.value)
  myChart.showLoading()
  
  try {
    // 获取中国地图数据 - 使用备用数据源
    let chinaJson;
    try {
      const response = await fetch('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
      chinaJson = await response.json()
    } catch (error) {
      console.warn('使用阿里云地图数据失败，尝试其他数据源')
      // 备用数据源
      const response = await fetch('https://echarts.apache.org/examples/data/asset/geo/china.json')
      chinaJson = await response.json()
    }
    
    myChart.hideLoading()
    
    // 注册中国地图
    echarts.registerMap('China', chinaJson)
    
    // 调试信息：打印地图区域名称和数据匹配情况
    const mapRegions = chinaJson.features?.map((f: any) => f.properties?.name) || []
    const dataNames = chinaData.value.map(d => d.name)
    
    console.log('地图区域名称 (前10个):', mapRegions.slice(0, 10))
    console.log('数据名称 (前10个):', dataNames.slice(0, 10))
    console.log('数据总数:', chinaData.value.length)
    
    // 检查数据匹配情况
    const matchedRegions = mapRegions.filter(region => 
      dataNames.some(dataName => dataName === region)
    )
    console.log('匹配的地区数量:', matchedRegions.length)
    console.log('匹配的地区:', matchedRegions.slice(0, 10))
    
    // 检查数据值范围
    const values = chinaData.value.map(d => d.value).filter(v => v > 0)
    console.log('数据值范围:', {
      min: Math.min(...values),
      max: Math.max(...values),
      count: values.length
    })
    
    const option = {
      title: {
        text: props.title,
        subtext: '数据来源：统计局',
        left: 'right',
        textStyle: {
          color: '#fff',
          fontSize: 18
        },
        subtextStyle: {
          color: '#ccc',
          fontSize: 12
        }
      },
      tooltip: {
        trigger: 'item',
        showDelay: 0,
        transitionDuration: 0.2,
        formatter: function(params: any) {
          return `${params.name}<br/>${params.value || 0} 人`
        }
      },
      visualMap: {
        type: 'continuous',
        right: '20px',
        bottom: '10%',
        min: 0,
        max: 13000,
        range: [0, 13000],
        realtime: true,
        calculable: true,
        inRange: {
          color: flowingColors[currentColorIndex]
        },
        text: ['高', '低'],
        textStyle: {
          color: '#fff',
          fontSize: 12
        },
        backgroundColor: 'rgba(0, 20, 60, 0.3)',
        borderColor: 'rgba(255, 255, 255, 0.2)',
        borderWidth: 1
      },
      toolbox: {
        show: false
      },
      series: [
        {
          name: '中国数据',
          type: 'map',
          roam: false,
          map: 'China',
          emphasis: {
            label: {
              show: true,
              color: '#fff'
            },
            itemStyle: {
              borderColor: 'rgba(255, 255, 255, 1)',
              borderWidth: 3,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
              shadowBlur: 10
            }
          },
          label: {
            show: false,
            color: '#fff'
          },
          itemStyle: {
            borderColor: 'rgba(255, 255, 255, 0.8)',
            borderWidth: 2,
            shadowColor: 'rgba(0, 0, 0, 0.2)',
            shadowBlur: 5
          },
          data: chinaData.value
        }
      ]
    }
    
    myChart.setOption(option)
    
    // 启动颜色流动动画
    startColorAnimation()
    
    // 响应式处理
    const handleResize = () => {
      myChart?.resize()
    }
    window.addEventListener('resize', handleResize)
    
  } catch (error) {
    console.error('加载地图数据失败:', error)
    myChart.hideLoading()
  }
}

// 颜色流动动画函数
const startColorAnimation = () => {
  if (colorAnimationTimer) {
    clearInterval(colorAnimationTimer)
  }
  
  colorAnimationTimer = setInterval(() => {
    if (!myChart) return
    
    // 切换到下一组颜色
    currentColorIndex = (currentColorIndex + 1) % flowingColors.length
    
    // 更新图表配置
    const option = {
      visualMap: {
        inRange: {
          color: flowingColors[currentColorIndex]
        }
      }
    }
    
    // 使用平滑过渡更新颜色
    myChart.setOption(option, {
      notMerge: false,
      lazyUpdate: false,
      silent: false
    })
  }, 3000) // 每3秒切换一次颜色
}

onMounted(() => {
  initChart()
})

onUnmounted(() => {
  // 清理颜色动画定时器
  if (colorAnimationTimer) {
    clearInterval(colorAnimationTimer)
    colorAnimationTimer = null
  }
  
  if (myChart) {
    myChart.dispose()
    myChart = null
  }
  window.removeEventListener('resize', () => {})
})
</script>

<style scoped>
.china-map-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: linear-gradient(135deg, #0a0e27 0%, #1a1f3a 25%, #2d3561 50%, #1a1f3a 75%, #0a0e27 100%);
}

.background-layers {
  position: relative;
  width: 100%;
  height: 100%;
}

.map-layer {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: contain;
  pointer-events: none;
}

.map-base {
  z-index: 1;
  opacity: 0.3;
}

.map-overlay {
  z-index: 2;
  opacity: 0.8;
}

.rotating {
  animation: rotate 20s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.echarts-layer {
  position: absolute;
  top: 80px;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 3;
  /* 添加微妙的发光效果增强流动感 */
  filter: drop-shadow(0 0 10px rgba(0, 212, 255, 0.3));
  animation: glow-pulse 4s ease-in-out infinite alternate;
}

@keyframes glow-pulse {
  0% {
    filter: drop-shadow(0 0 10px rgba(0, 212, 255, 0.3));
  }
  100% {
    filter: drop-shadow(0 0 20px rgba(0, 212, 255, 0.6));
  }
}

/* 科技风背景 */
.tech-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  overflow: hidden;
}

.grid-lines {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: 
    linear-gradient(rgba(0, 212, 255, 0.1) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 212, 255, 0.1) 1px, transparent 1px);
  background-size: 50px 50px;
  animation: grid-move 20s linear infinite;
}

@keyframes grid-move {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(50px, 50px);
  }
}

.floating-particles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: 
    radial-gradient(2px 2px at 20px 30px, rgba(0, 212, 255, 0.8), transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(0, 255, 136, 0.6), transparent),
    radial-gradient(1px 1px at 90px 40px, rgba(255, 107, 107, 0.7), transparent),
    radial-gradient(1px 1px at 130px 80px, rgba(255, 167, 38, 0.5), transparent),
    radial-gradient(2px 2px at 160px 30px, rgba(84, 112, 198, 0.6), transparent);
  background-repeat: repeat;
  background-size: 200px 100px;
  animation: float 15s ease-in-out infinite;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) translateX(0px);
  }
  33% {
    transform: translateY(-10px) translateX(10px);
  }
  66% {
    transform: translateY(5px) translateX(-5px);
  }
}

/* 返回按钮 */
.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 10;
  background: linear-gradient(135deg, rgba(0, 212, 255, 0.8), rgba(0, 150, 255, 0.9));
  border: 2px solid #00d4ff;
  border-radius: 8px;
  color: #ffffff;
  padding: 10px 20px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 15px rgba(0, 212, 255, 0.3);
}

.back-button:hover {
  background: linear-gradient(135deg, rgba(0, 212, 255, 1), rgba(0, 150, 255, 1));
  border-color: #00f4ff;
  box-shadow: 0 6px 20px rgba(0, 212, 255, 0.6);
  transform: translateY(-2px);
}

.back-icon {
  font-size: 18px;
  font-weight: bold;
}

.back-text {
  font-size: 14px;
}
</style>